package com.ayoldi.podcastusbsync.synchronizer;

import java.io.File;
import java.util.Iterator;

import javax.swing.filechooser.FileSystemView;


import org.apache.log4j.Logger;

public class USBDeviceCheckerThread extends Thread{

	static Logger LOG = Logger.getLogger(USBDeviceCheckerThread.class);
	
	private String deviceLabel;
	private String deviceFolder;
	
	private USBDeviceSynchronizer usbDeviceSynchronizer;	
	long checkIntervalMs;
	
	private boolean stopped=false;
	


	public boolean isStopped() {
		return stopped;
	}

	public void setStopped(boolean stopped) {
		this.stopped = stopped;
	}

	public USBDeviceCheckerThread(USBDeviceSynchronizer synchronizer, long checkIntervalMs){
		this.deviceLabel=synchronizer.deviceConfiguration.getDeviceLabel();
		this.deviceFolder=synchronizer.deviceConfiguration.getDeviceFolder();
		this.usbDeviceSynchronizer=synchronizer;
		this.checkIntervalMs=checkIntervalMs;
		
	}
	
	public void run() {
		LOG.info("Starting USB device checker thread for device: "+deviceLabel);
		while (!stopped && deviceLabel!=null && deviceFolder!=null && deviceLabel.length()>0 && deviceFolder.length()>0){			
			File[] roots=File.listRoots();
			if (roots!=null){
				for (File currentDrive : roots){
					LOG.debug("Device found on system: "+FileSystemView.getFileSystemView().getSystemDisplayName (currentDrive));
					String volumeLabel = USBDeviceSynchronizerUtils.getVolumeLabel(currentDrive);
					File absolutePodcastPath=new File(currentDrive, deviceFolder);
					if (volumeLabel!=null && volumeLabel.equalsIgnoreCase(deviceLabel) && currentDrive.canWrite() && absolutePodcastPath.exists()){
						LOG.info("Target device found: "+volumeLabel+". Synchronizing...");
						usbDeviceSynchronizer.sync(absolutePodcastPath);
						continue;
					}
				}
				
				
			}			
			
			// SI NO SE ENCUENTRA POR USB STORAGE MIRAMOS EN MTP
			// POR DEVICE NAME
			String deviceId=USBDeviceSynchronizerUtils.searchOnMTPDevicesByDeviceName(deviceLabel);
			// Y SINO POR FILENAME
			if (deviceId==null){
				deviceId=USBDeviceSynchronizerUtils.searchOnMTPDevicesByFilename(deviceLabel);
			}
			
			if (deviceId!=null){
				usbDeviceSynchronizer.syncMTP(deviceFolder,deviceId);
			}
			
			try {
				LOG.debug("Going to sleep for (ms): "+checkIntervalMs);
				Thread.sleep(checkIntervalMs);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
	
	}
	
	
		 
	
	
	public synchronized boolean isStopThread() {
		return stopped;
	}

	public synchronized void setStopThread(boolean stopThread) {
		this.stopped = stopThread;
	}
	
	
	
}
